package com.hyper_yang._03_designpatterns.pattern.creational_patterns;

import java.lang.reflect.Constructor;

/**
 * @version: 1.0.0
 * @author: sakiko
 * time: 2025/10/9 0:50
 * description: 反射破坏单例模式
 */
public class BreakSingletonByInvoke {
    public static void main(String[] args) throws Exception {
        // 获取 LSingleton对象的字节码对象
        Class<LSingleton> clazz = LSingleton.class;
        // 获取无参构造方法
        Constructor<LSingleton> declaredConstructor = clazz.getDeclaredConstructor();
        // 获取对象
        declaredConstructor.setAccessible(true); // java.lang.IllegalAccessException
        LSingleton lSingleton = declaredConstructor.newInstance(); // todo: 在构造器内操作可以防治反射破坏单例模式
        LSingleton lSingleton2 = declaredConstructor.newInstance();
        System.out.println(lSingleton == lSingleton2); // false 反射破坏了单例模式
    }
}

class LSingleton {
    private static boolean isFirst = true;

    private LSingleton() {
        synchronized (LSingleton.class) {
            if (!isFirst) {
                throw new RuntimeException("已存在本对象实例");
            }
            isFirst = false;
        }
    }

    private static volatile LSingleton instance;

    public LSingleton getInstance() {
        if (null == instance) {
            synchronized (LSingleton.class) {
                if (null == instance) {
                    instance = new LSingleton();
                }
            }
        }
        return instance;
    }
}
